<template>
  <view class="battery-container">
    <view class="battery-wrapper">
      <image :src="getBatteryIcon(batteryLevel)" mode="widthFix"></image>
      <view class="battery-percentage">{{ batteryLevel }}</view>
    </view>
  </view>
</template>
 
<script lang="ts" setup>
import { computed } from 'vue';
 
// 定义 props 接收外部传入的电量值
interface Props {
  level: number;
}
 
const props = defineProps<Props>();
 
// 计算属性，确保电量值在合理范围内（0 - 100）
const batteryLevel = computed(() => {
  return Math.max(0, Math.min(100, props.level));
});
 
// 根据电量百分比返回对应的图标路径
const getBatteryIcon = (level: number): string => {
  if (level >= 96 && level <= 100) {
    return '/static/icons/96_100.png';
  } else if (level >= 66 && level < 95) {
    return '/static/icons/66_95.png';
  } else if (level >= 36 && level < 65) {
    return '/static/icons/36_65.png';
  } else if (level >= 6 && level < 36) {
    return '/static/icons/6_35.png';
  } else {
    return '/static/icons/0_5.png';
  }
};
</script>
 
<style scoped>
.battery-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
 
.battery-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
 
image {
  width: 46rpx;
  height: 28rpx;
  display: block;
}
 
.battery-percentage {
  position: absolute;
  font-family: Source Han Sans, Source Han Sans;
  font-weight: 350;
  font-size: 18rpx;
  color: #000000;
  line-height: 18rpx;
  text-align: center;
  /* 居中对齐 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>